/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.krossk.util;


import br.com.krossk.jpa.JPAFactory;
import br.com.krossk.model.Arquivo;
import br.com.krossk.model.Usuario;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

/**
 *
 * @author Henrique
 */
public class Counter {
    public static long contarTotalArquivos(){
        EntityManager em = JPAFactory.getEntityManager();
        Query q = em.createQuery("SELECT COUNT (a.idArquivo) FROM Arquivo a");
        try{
            return (Long)q.getSingleResult();
        }catch(NoResultException nre){
            return 0;
        }finally{
            em.close();
        }
    }

    public static long contarTotalUsuarios(){
        EntityManager em = JPAFactory.getEntityManager();
        Query q = em.createQuery("SELECT COUNT (u.idUsuario) FROM Usuario u");
        try{
            return (Long)q.getSingleResult();
        }catch(NoResultException nre){
            return 0;
        }finally{
            em.close();
        }
    }

    public static List<Arquivo>listarMaisRecentes(){
        EntityManager em = JPAFactory.getEntityManager();
        Query q = em.createQuery("FROM Arquivo a ORDER BY a.idArquivo desc");
        q.setFirstResult(0);
        q.setMaxResults(3);
        
        try{
            return q.getResultList();
        }catch(Exception ex){
            return null;
        }finally{
            em.close();
        }
        
    }
    public static List<Arquivo>listarMaisRecentes(Usuario u){
        EntityManager em = JPAFactory.getEntityManager();
        Query q = em.createQuery("FROM Arquivo a WHERE a.usuario = :usuario ORDER BY a.idArquivo desc");
        q.setParameter("usuario", u);
        q.setFirstResult(0);
        q.setMaxResults(3);

        try{
            return q.getResultList();
        }catch(Exception ex){
            return null;
        }finally{
            em.close();
        }

    }

    public static List<Arquivo> listarBuscaUsuario(int idUsuario){
        EntityManager em = JPAFactory.getEntityManager();
        Query q = em.createQuery("SELECT u.arquivoCollection FROM Usuario u WHERE u.idUsuario = :idUsuario");
        q.setMaxResults(2);
        q.setParameter("idUsuario", idUsuario);

        //Usuario u = em.find(Usuario.class, idUsuario);
        //return (List)u.getArquivoCollection();
        try{
            return q.getResultList();
        }catch(NullPointerException npe){
            return null;
        }finally{
            em.close();
        }
    }
}
